package com.h2cloud.ReactorTest.reactor.server.multi;

import com.h2cloud.ReactorTest.reactor.server.Acceptor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.locks.LockSupport;

/**
 * @Package: com.h2cloud.ReactorTest.reactor.server
 * @ClassName: MainReactor
 * @Author: wulongkai
 * @CreateTime: 2024/7/23 15:59
 * @Description:
 */
public class MainReactor implements Runnable {

    private final Selector selector;

    public MainReactor(int port) throws IOException {
        // 开多路复用器
        selector = Selector.open();
        // 服务端创建listen-socket管道
        ServerSocketChannel listenSocketChannel = ServerSocketChannel.open();
        // 设置为非阻塞
        listenSocketChannel.configureBlocking(false);
        // 绑定监听端口
        listenSocketChannel.socket().bind(new InetSocketAddress(port));
        // 将listen-socket管道绑定到主Reactor的多路复用器上
        // 并且主Reactor上只会注册listen-socket管道，用于监听ACCEPT事件
        listenSocketChannel.register(selector, SelectionKey.OP_ACCEPT,
                new MainAcceptor(listenSocketChannel));
    }

    @Override
    public void run() {
        while (!Thread.interrupted()) {
            try {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterable = selectionKeys.iterator();
                while (iterable.hasNext()) {
                    // 对事件进行分发
                    dispatch(iterable.next());
                    iterable.remove();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            LockSupport.parkNanos(1000 * 1000 * 1000);
        }
    }

    private void dispatch(SelectionKey selectionKey) {
        // 获取事件附加器，只会是Acceptor
        Runnable attachment = (Runnable) selectionKey.attachment();
        if (attachment != null) {
            attachment.run();
        }
    }

}

